<?php
if (!defined('PLUGINFRAME'))exit('hacking attempt');

class common{
    private $_data=array();
    
    public  function __construct(){
        
    }
    protected function display(){
        global $lang;
        $tplFile=tpl.'/'.MOD.'/'.ACT.'.html';
        if (!file_exists($tplFile))
          throw new Exception($lang['FILE_NOT_EXIST']);
        $tplCon=file_get_contents($tplFile);
        $compiledFile=$this->parseTemplate($tplCon);
        ob_start();
        ob_implicit_flush(0);
        extract($this->_data,EXTR_OVERWRITE);
        include $compiledFile;
        $tplCon=ob_get_clean();
        eval('?>'.$tplCon);
        
    }
    
    private function parseTemplate($content){
        global $lang,$cfg;
        $name=md5(tpl.'/'.MOD.'/'.ACT.'.php');
        $filecache=runtime.'/'.$name.'.php';
        $cacheExist=false;
        if(file_exists($filecache) && !$cfg['debug']){
            $cache_expire=time()-fileatime($filecache);
            $cache_expire<$cfg['cache_time'] && $cacheExist=true;
        }
        if ($cacheExist){
            return $filecache;
        }else {
            if ($content){
                $content=$this->replaceTags($content);
                file_put_contents($filecache, '<?php !defined("PLUGINFRAME") && exit;?>'.$content);
            }else {
               exit($lang['TPL_ERROR']);
            }
        }
        return $filecache;
        
    }
    
    private function subtemplate($stpl){
        $stplCon=file_get_contents(APP_PATH.'/'.$stpl);
        return $this->replaceTags($stplCon);
    }
    
    private function loop($lpCon){
        
    }
    
    private function replaceTags($html){
        $html=preg_replace("/[\r\n\t]*\{subtemplate\s([^}]+?)\}[\r\n\t]*/esi", "\$this->subtemplate('\\1')", $html);
        $html=preg_replace("/[\n\r\t]*\{echo\s+(.+?)\}[\n\r\t]*/ies", "\$this->stripvtags('<?php echo \\1; ?>')", $html);
//        $var_regexp = "((\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(\-\>)?[a-zA-Z0-9_\x7f-\xff]*)(\[[a-zA-Z0-9_\-\.\"\'\[\]\$\x7f-\xff]+\])*)";
        $html = preg_replace("/\s*\{loop\s(.+?)\}\s*/esi", "\$this->_loop('\\1')", $html);
        $html = preg_replace("/\s*\{\/loop}\s*/esi", "\$this->_loop('',true)", $html);
        $html = preg_replace("/\s*\{if\s(.+?)\}\s*/esi", "\$this->_if('\\1')", $html);
        $html = preg_replace("/\s*\{elseif\s(.+?)\}\s*/esi", "\$this->_elseif('\\1')", $html);
        $html = preg_replace("/\s*\{else\s\/}\s*/esi", "\$this->_else()", $html);
        $html = preg_replace("/\s*\{\/if}\s*/esi", "\$this->_if('',true)", $html);
        $html = preg_replace("/\s*\{(\\\$[^\s\|]+?)\}\s*/si", "<?php echo \\1;?>", $html);
        $html = preg_replace("/\s*\{(\\\$[^\s]+?)\|([a-z_]+?)=(.*?)\}\s*/si", "<?php echo \\2(\\1,\\3);?>", $html);
        $html = preg_replace("/\s*\{(\\\$[^\s]+?)\|([a-z_]+?)\}\s*/si", "<?php echo \\2(\\1);?>", $html);
        return $html;
//      $content=preg_replace("/{loop\s([^}]*?)}/esi", "\$this->loop('\\1')", $content);
        
    }
    
    
    public function assgin($name,$value){
        //if ($name!='' && $value!='')
           $this->_data[$name]=$value;
    }
    
    private function _loop($lpcode,$close=false){
        $lpparam=trim($lpcode);
        $result='';
        if ($lpparam){
            $lpparam=explode(' ', $lpparam);
            if (count($lpparam)==1){
                $result.='<?php foreach('.$lpparam[0].' as $item):?>';
            }elseif (count($lpparam)==2){
                $result.='<?php foreach('.$lpparam[0].' as '.$lpparam[1].'):?>';
            }elseif (count($lpparam)==3){
                $result.='<?php foreach('.$lpparam[0].' as '.$lpparam[1].'=>'.$lpparam[2].'):?>';
            }
        }elseif ($close){
            $result.='<?php endforeach;?>';
        }
        return $result;
    }
    
    private function _if($ifCode,$close=false){
        $result='';
        $search=array('lt','gt','le','ge');
        $replace=array('<','>','<=','>=');
        $ifParam=trim($ifCode);
        if ($ifParam){
            $result.='<?php if('.str_replace($search, $replace, $ifParam).'):?>';
        }elseif ($close){
            $result.='<?php endif;?>';
        }
        return $result;
    }
    
    private function _elseif($ifCode){
        $result='';
        $ifParam=trim($ifCode);
        if ($ifParam){
            $result.='<?php elseif('.$ifParam.'):?>';
        }
        return $result;
    }
    
    private function _else(){
        return '<?php else:?>';
    }
    
    private function stripvtags($expr, $statement = '') {

        $expr = str_replace("\\\"", "\"", preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", $expr));

        $statement = str_replace("\\\"", "\"", $statement);

        return $expr.$statement;

    }
    
    private function addquote($var) {

        return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var));

    }
    
    public function dcategory(&$cates,$cid,$sFlag=true){
        $aCate=array();
        foreach ($cates as $cKey=>$cVal){
            $aCate[$cVal][]=$cKey;
        }
        return $this->getCategory($cates, $cid ,$aCate,$sFlag);
    }
    public function getCategory(&$cates,$cid,&$valCount,$sFlag=true){  //sFlag为真时找父类   父类cate[id] 子类array_search()
        static $result=array();
        $sVal=array_search($cid, $cates);
        if ($sFlag){
            if ($sVal){
                if (count($valCount[$cid])>1)array_unshift($result, $valCount[$cid]);
                else array_unshift($result, $cid);
                $this->getCategory($cates, $cates[$cid], $valCount,$sFlag);
            }else {
                array_unshift($result, $cid);
            }
/*            if (!$sVal || $cates[$cid]==0 || ($sVal &&!isset($valCount[$cid]) || count($valCount[$cid])<=1))
              array_unshift($result,$cid);
            else 
              array_unshift($result, $valCount[$cates[$cid]]);
            if ($cates[$cid]!=0 )
                $this->getCategory($cates,$cates[$cid],$valCount,$sFlag);*/
        }else {
            if(isset($valCount[$cid])){
                if (count($valCount[$cid])>1){
                   array_push($result, $valCount[$cid]);
                   //$sVal=$cid+count($valCount[$cid]);
                }else{
                   array_push($result, $cid);
                }
                $this->getCategory($cates, $sVal, $valCount,$sFlag);
            }else {
                array_push($result, $cid);
            }
            
/*            if (!$sVal || ($sVal && count($valCount[$cid])<=1))
              array_push($result,$cid);//array_unshift($result,$cid);
            else 
              array_push($result,$valCount[$cid]);//array_unshift($result, $valCount[$cates[$cid]]);
            
            if ($sVal)$this->getCategory($cates,$sid,$valCount,$sFlag); */         
        }
/*        if (is_array($cates) && $cates  && $cid){
            if ($sid=array_search($cid, $cates)){//pid为主键id
                array_unshift($result, $sid);
                if ($cates[$sid]==0)array_unshift($result, $cid);
                else dcategory($cates,$sid);
            }elseif (is_numeric($cates[$cid])){
                array_unshift($result, $cid);
                if ($cates[$cid]!=0)dcategory($cates,$cates[$cid]);
            }
            foreach ($cates as $cKey=>$cVal){
                in_array($cid, $cVal);
            }
        }*/
        return $result;
    }    
    
    //@lg  图片等比缩放
    public function imageResize($file,$maxWidth=286,$baseUrl=''){
        $pw=$maxWidth;
        $file=$baseUrl==''?APP_PATH.'/'.$file:$baseUrl.'/'.$file;
        $pinfo=getimagesize($file);//exit(var_export($pinfo,true));
        $pb=$pw/$pinfo[0];
        $ph=(int)floor($pinfo[1] * $pb);
        return array('w'=>$pw,'h'=>$ph);
   }


}